package liumengbaio.lolzhangyoubao.Activity.Activity;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import liumengbaio.lolzhangyoubao.Activity.InFo.City;
import liumengbaio.lolzhangyoubao.Activity.View.PinnedSectionListView;
import liumengbaio.lolzhangyoubao.R;

/**
 * Created by lanouhn on 16/9/2.
 */
public class CityActivity extends AppCompatActivity implements View.OnClickListener {
    private ArrayList<Data> data;
    private ArrayList<City> list_city;
    private TextView A;
    private PinnedSectionListView pslv;
    private SharedPreferences sp;
    private SharedPreferences.Editor editor;
    private Button city_head_left_title;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.city_activity);
        sp = getSharedPreferences("userInfo", MODE_PRIVATE);
        editor=sp.edit();
        String[] s = {"当前城市", "a", "b", "c", "d", "e", "f"
                , "g", "h", "i", "j", "k", "l"
                , "m", "n", "o", "p", "q", "r"
                , "s", "t", "w", "x"
                , "y", "z"};
        initView();
        initData();
        data = new ArrayList<Data>();
        for (String n : s) {
            Data group = new Data();
            group.type = Data.GROUP;
            group.city.setName(n);
            data.add(group);
            for (int i = 0; i < list_city.size(); i++) {
                Data child = new Data();
                child.type = Data.CHILD;
                if (i == 0) {
                    if ("当前城市".equals(n)) {
                        child.city.setName(sp.getString("city", "未知城市"));
                        data.add(child);
                    }

                } else {
                    if (list_city.get(i).getEnname().subSequence(0, 1).equals(n)) {
                        child.city.setName(list_city.get(i).getName());
                        data.add(child);
                    }
                }
            }
        }

        pslv = (PinnedSectionListView) findViewById(R.id.pslv);
        pslv.setDivider(null);
        pslv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                editor.putString("selectCity",data.get(position).city.getName());
                editor.commit();
                finish();
            }
        });
        MyAdapter mMyAdapter = new MyAdapter(this, -1);
        pslv.setAdapter(mMyAdapter);
    }

    private void initData() {
        city_head_left_title.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void initView() {
        city_head_left_title= (Button) findViewById(R.id.city_head_left_title);
        textview_declare();
        String res = readFile("area.json");
        list_city = new ArrayList<>();
        try {
            JSONArray array = new JSONArray(res);
            for (int i = 0; i < array.length(); i++) {
                JSONObject json = (JSONObject) array.get(i);
                City obj = new City();
                if (json.has("id") && !json.isNull("id")) {
                    obj.setId(json.getString("id"));
                }
                if (json.has("name") && !json.isNull("name")) {
                    obj.setName(json.getString("name"));
                }
                if (json.has("enname") && !json.isNull("enname")) {
                    obj.setEnname(json.getString("enname"));
                }
                list_city.add(obj);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View v) {
        int $ = v.getId() - R.id.A;
        int tag = Integer.parseInt(v.getTag() + "");
        pslv.setSelection(tag);
    }

    // 定义一个存放数据类型的类
    private class Data {
        public static final int GROUP = 0;
        public static final int CHILD = 1;
        public int type;
        public City city = new City();
        // 2个type child和group
        public static final int TYPE_COUNT = 2;

    }

    // 定义适配器要实现PinnedSectionListAdapter接口 来调用isItemViewTypePinned(int
    // viewType)方法
    private class MyAdapter extends ArrayAdapter implements PinnedSectionListView.PinnedSectionListAdapter {
        private LayoutInflater flater;

        public MyAdapter(Context context, int resource) {
            super(context, resource);
            flater = LayoutInflater.from(context);
        }

        @Override
        public int getCount() {
            return data.size();
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            int type = getItemViewType(position);
            switch (type) {
                case Data.GROUP:
                    if (convertView == null)
                        convertView = flater.inflate(R.layout.city_item_select_height, null);

                    TextView tv1 = (TextView) convertView.findViewById(android.R.id.text1);

                    tv1.setText(data.get(position).city.getName());
                    tv1.setBackgroundColor(Color.parseColor("#9925262d"));
                    tv1.setTextSize(19);

                    break;

                case Data.CHILD:
                    if (convertView == null)
                        convertView = flater.inflate(R.layout.city_item_select_height_content, null);
                    TextView tv2 = (TextView) convertView.findViewById(android.R.id.text1);
                    tv2.setText(data.get(position).city.getName());
                    tv2.setTextSize(19);
                    break;
                default:
                    break;
            }
            return convertView;
        }

        // 返回列表类型 两种 child和group
        @Override
        public int getViewTypeCount() {

            return Data.TYPE_COUNT;
        }

        // 获取列表类型
        @Override
        public int getItemViewType(int position) {
            return data.get(position).type;
        }

        @Override
        public Object getItem(int position) {
            return data.get(position);
        }

        // 假设此方法返回皆为false。那么PinnedSectionListView将退化成为一个基础的ListView.
        // 只不过退化后的ListView只是一个拥有两个View Type的ListView。
        // 从某种角度上讲，此方法对于PinnedSectionListView至关重要，因为返回值true或false，将直接导致PinnedSectionListView是一个PinnedSectionListView，还是一个普通的ListView。
        @Override
        public boolean isItemViewTypePinned(int viewType) {
            boolean type = false;
            switch (viewType) {
                case Data.GROUP:

                    type = true;

                    break;

                case Data.CHILD:

                    type = false;

                    break;
                default:
                    type = false;
                    break;
            }
            return type;
        }

    }

    // 打开json数据文件
    private String readFile(String fileName) {
        String result = "";
        try {
            // 读取assets中的文件，文件内容写入一个输入流里边
            //InputStream is = context.getAssets().open("hero/" + id + ".json");
            InputStream is = getAssets().open(fileName);
            // 按行读取
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            // 创建一个临时的字符串来保存每一行的数据
            String line = "";
            // 循环读取文件内容，每次读取一行，如果读取到文件末尾，则读取的内容为null
            while ((line = br.readLine()) != null) {
                result += line;// 将每次读取的内容给最终的result
            }
            // 关闭流,先开的关
            br.close();
            isr.close();
            is.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 循环生命textview
     */
    private void textview_declare() {
        for (int $ = R.id.A; $ < R.id.Z + 1; $++) {
            A = (TextView) findViewById($);
            A.setOnClickListener(this);
        }
    }
}
